package org.ielts.action.security;

import java.net.URISyntaxException;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;

import org.apache.http.client.utils.URIBuilder;
import org.ielts.action.BaseAction;
import org.ielts.domain.base.Campus;
import org.ielts.domain.base.Department;
import org.ielts.domain.security.Role;
import org.ielts.domain.security.User;
import org.ielts.service.CampusService;
import org.ielts.service.security.DepartmentService;
import org.ielts.service.security.RoleService;
import org.ielts.service.security.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import com.yifeng.ProfileContext;
import com.yifeng.crypto.CryptoUtils;
import com.yifeng.dto.DtoRow;
import com.yifeng.dto.utils.DtoUtil;
import com.yifeng.modules.annotations.Module;
import com.yifeng.modules.annotations.Operation;
import com.yifeng.profile.Profile;
import com.yifeng.security.groups.Group;
import com.yifeng.security.groups.GroupCollection;
import com.yifeng.security.privilege.Privilege;
import com.yifeng.security.privilege.Privileges;
import com.yifeng.security.users.User.Status;
import com.yifeng.struts2.action.FormAction;
import com.yifeng.utils.JsonResultBuilder;
import com.yifeng.utils.PageUtils;
import com.yifeng.web.Pagers;
import com.yifeng.web.Paginations;

import static com.yifeng.struts2.RequestParameters.*;
import static com.yifeng.struts2.ResultParameters.*;
import static com.yifeng.struts2.ResultConstants.*;
import static com.yifeng.struts2.ActionUtils.*;

@Module(namespaceName = "security")
public class UserAction extends BaseAction {

	@Autowired
	UserService userService;

	@Operation(result = FILL)
	public String listUser() throws URISyntaxException {
		String name = form.readString("name");

		Pageable paginations = getPageable(15);

		Page<User> users = userService.listUser(name, paginations);

		put("users", users);
		put(PAGINATIONS, new Paginations(users));

		return FILL;
	}

	@Operation(result = FILL)
	public String selectUser() {
		String name = form.readString("name");
		Pageable pageable = getPageable(15);

		Page<User> users = userService.listUser(name, pageable);
		put("users", users);

		put(PAGINATIONS, new Paginations(users));

		return FILL;
	}

	@Autowired
	RoleService roleService;

	@Autowired
	DepartmentService departmentService;

	@Autowired
	CampusService campusService;

	@Operation(result = FILL)
	public String createUser() {

		Iterable<Campus> campuses = campusService.findAll();
		put("campuses", campuses);

		Iterable<Role> roles = roleService.listAllRole();
		put("roles", roles);

		Iterable<Department> departments = departmentService.findAll();
		put("departments", departments);

		return FILL;
	}

	@Operation(result = JSON)
	public String doCreateUser() {

		String name = form.readString("name").trim();
		String title = form.readString("title");
		String[] roleIds = form.readStrings("roleId");
		String departmentId = form.readString("departmentId");
		String loginName = form.readString("loginName");

		User user = userService.findByLoginName(loginName);
		if (user == null) {
			Date entryTime = valueReader.name("entryTime").defaultValue(null).dateValue("yyyy-MM-dd");
			String campus = form.readString("campus");
			String no = form.readString("no");

			userService.createUser(loginName, name, title, roleIds, departmentId, campus, no, entryTime);

			setJson(JsonResultBuilder.success(true).msg("添加新用户成功。").json());
		} else {
			setJson(JsonResultBuilder.success(false).msg("已存在同登录名的用户，请修改登录名重试。").json());
		}

		return JSON;
	}

	@Operation(result = JSON)
	public String doRemoveUser() {
		String id = form.readString("id");

		// TODO 关系检查
		userService.removeUser(id);

		setJson(JsonResultBuilder.success(true).msg("删除用户成功。").json());
		return JSON;
	}

	@Operation(result = FILL)
	public String modifyUser() {
		String id = form.readString("id");

		Iterable<Campus> campuses = campusService.findAll();
		put("campuses", campuses);

		User user = userService.findUser(id);
		put("user", user);

		Iterable<Role> roles = roleService.listAllRole();
		put("roles", roles);

		Iterable<Department> departments = departmentService.findAll();
		put("departments", departments);

		return FILL;
	}

	@Operation(result = FILL)
	public String viewUser() {
		String id = form.readString("id");

		User user = userService.findUser(id);
		put("user", user);

		Iterable<Role> roles = roleService.listAllRole();
		put("roles", roles);

		Collection<Privilege> privileges = Privileges.getAllPrivileges();
		put("privileges", privileges);

		Iterable<Privilege> returnList = authorization.findPrivilegesByUser(id);

		put("grants", returnList);

		String userId = Profile.getInstance().getUserId();
		if (id.equals(userId)) {
			put("self", true);
		}

		return FILL;
	}

	@Operation(result = JSON)
	public String doModifyUser() {
		String id = form.readString("id");
		String name = form.readString("name");
		String loginName = form.readString("loginName");
		String title = form.readString("title");
		String[] roleIds = form.readStrings("roleId");

		User existsUser = userService.findByLoginName(loginName);

		if (existsUser != null && !existsUser.getId().equals(id)) {
			setJson(JsonResultBuilder.success(false).msg("已存在同登录名的用户。").json());
		} else {
			Date entryTime = valueReader.name("entryTime").defaultValue(null).dateValue("yyyy-MM-dd");
			String campus = form.readString("campus");
			String no = form.readString("no");

			String departmentId = form.readString("departmentId");

			userService.modifyUser(id, loginName, name, title, campus, no, roleIds, departmentId, entryTime);
			setJson(JsonResultBuilder.success(true).msg("修改用户成功。").json());
		}

		return JSON;
	}

	@Operation(result = FILL)
	public String changePwd() {
		String id = form.readString("id");

		User user = userService.findUser(id);

		put("user", user);

		return FILL;
	}

	@Operation(result = FILL)
	public String doChangePwd() {
		String id = form.readString("id");
		String name = form.readString("name");
		String oldPwd = form.readString("oldPwd");
		String newPwd = form.readString("newPwd");

		Status status = userService.checkUserStatus(name, oldPwd);

		if (status != Status.PasswordError) {
			userService.changePwd(id, newPwd);

			setJson(JsonResultBuilder.success(true).msg("设置新密码成功。").json());
		} else {

			setJson(JsonResultBuilder.success(false).msg("旧密码输入错误，无法使用新密码。").json());
		}

		return JSON;
	}

	@Operation(result = JSON)
	public String doResetPwd() {
		String id = form.readString("id");

		userService.resetPassword(id);

		setJson(JsonResultBuilder.success(true).msg("已充值用户密码为初始密码。").json());

		return JSON;
	}

}
